<?php

require_once 'Pipes/FileSystem/File/Finder.php';
require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Controller.php';
require_once 'PipesImpl/Route.php';
require_once 'PipesImpl/User/Credentials.php';
require_once 'PipesImpl/View.php';

class Pipes_Dispatcher
{
	private $_config = null;
	private $_controller = null;

	public function __construct(PipesImpl_Config $config, PipesImpl_Controller $controller) {
		$this->_config = $config;
		$this->_controller = $controller;
	}

	public function dispatch(PipesImpl_Route $route, PipesImpl_User_Credentials $credentials = null) {
		// catch any process calls
		$name = new Pipes_Value_Template_CamelCapsToDatabase($this->_controller->getName());
		if (!empty($_POST['pipes']['action'][$name->value]) && isset($_POST[$name->value])) {
			$this->_controller->process($_POST[$name->value]);
		}

		$callback = $this->_controller->findExecutable($route, $credentials);
		$controllerReturn = call_user_func_array($callback->value, $route->extras);

		if (!isset($route->page_type) || isset($_GET['isAjax'])) {
			return $controllerReturn;
		}

		$pageTypeClass = 'Pipes_Controller_PageType_' . ucfirst(strtolower($route->page_type));
		$finder = new Pipes_FileSystem_File_Finder();
		$finder->findByClass($pageTypeClass)->requireOnce();
		$pageType = new $pageTypeClass($this->_config, $this->_controller);
		return $pageType->render($controllerReturn);
	 
	}
}
